package com.yuan.fullstackback.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.yuan.fullstackback.mapper.SysUserMapper;
import com.yuan.fullstackback.model.userRequest.UserEntityBody;
import com.yuan.fullstackback.pojo.SysUser;
import com.yuan.fullstackback.service.ISysUserService;
import com.yuan.fullstackback.utils.Md5Util;
import com.yuan.fullstackback.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * 用户 业务层处理
 */
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        SysUser sysUser = userMapper.selectUserByUserName(userName);
        // 判断是否查询到
        if (ObjectUtil.isEmpty(sysUser)) return null;
        return sysUser;
    }

    /**
     * 注册用户信息
     *
     * @param registerUser 注册用户
     * @return 结果
     */
    @Override
    @Transactional
    public boolean registerUser(UserEntityBody registerUser) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(registerUser, user);
        user.setLoginDate(new Date());
        user.setDelFlag("0"); //删除标志（0代表存在 2代表删除）
        user.setStatus("0"); //帐号状态（0正常 1停用）
        user.setEmail(user.getUserName()); //帐号状态（0正常 1停用）
        user.setPassword(Md5Util.getMD5String(user.getPassword())); //用户部分数据需要加密存储：密码
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUserInfo(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param avatarUrl 头像路径
     * @return 结果
     */
    @Override
    public int updateUserAvatar(String avatarUrl) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        return userMapper.updateUserAvatar((Integer) claims.get("userId"), avatarUrl);
    }

    /**
     * 修改用户密码
     *
     * @param newPassword 新密码
     * @return 结果
     */
    @Override
    public int  resetUserPwd(String newPassword) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        return userMapper.resetUserPwd((Integer) claims.get("userId"), newPassword);
    }
}
